/* -----------------
* brief
* 1. this is code gen by tools
 */

package service

import (
	"errors"
	"saas_sys_base/common"
	// "saas_sys_base/config"
	// configService "saas_sys_base/modules/config/service"
)
import . "saas_sys_base/modules/user/models"

type MiniAppUserService struct {
	UserService
	appTenantUserRelService AppTenantUserRelService

	// add your model here
}

var _ UserServiceInterface = (*MiniAppUserService)(nil)


//自定义函数
func (t *MiniAppUserService) userLogin(whoApp common.Who, code string) (user *WxUser, tokenString string, err error) {
	//废弃函数
	return
}

/*
whoAppTenant:表示要登录的tenantApp
uid:为从sysToken中解析出的uid
 */
func (t *MiniAppUserService) UserLogin(tenantAppWho common.Who, uid int64/*, MiniAppId int64, tid int64*/) (tokenString string, err error) {

	//登录后，使用得到的Uid，组合成一个表示user的who对象
	whoUser := common.NewWho(tenantAppWho.TenantId, tenantAppWho.MiniAppId, uid)
	_, userRelTokenString, err := t.appTenantUserRelService.userLogin(*whoUser/*MiniAppId, tid, sysUser.Id*/) //这个登录就是多租户的关系表，建立appid、租户id、Uid
	if err != nil {
		return "", err
	}

	return userRelTokenString, nil
}


func (t *MiniAppUserService) CheckToken(passToken string, timestamp string) (userWho *common.Who, loginuser *LoginUser, err error) {
	userRel, err := t.appTenantUserRelService.CheckUserToken(passToken, timestamp)
	if err != nil {
		return nil, nil, err
	}

	/*sysUser := t.GetUserById(userRel.Uid)
	if sysUser == nil {
		return nil, errors.New("找不到用户")
	}

	wxUser := t.GetWxUserById(sysUser.WxUid)
	if sysUser == nil {
		return nil, errors.New("找不到用户")
	}

	user = new(LoginUser)
	user.User = sysUser
	user.WxUser = wxUser*/
    userWho = &common.Who{
    	TenantId:userRel.TenantId,
    	MiniAppId:userRel.MiniAppId,
    	Uid:userRel.Uid,
	}

	//返回参数loginuser,这里就不查询了，直接返回nil，少做一些操作
	return userWho, nil, nil

}

func (t *MiniAppUserService) ThirdLogin(wxUid int64) (UnionUser *User, err error) {
	//查看是否注册过，如果没有
	var user *User
	user = t.UserService.tbUser.RecodeByWxUid(wxUid)

	if user == nil {
		var item2add User
		item2add.WxUid = wxUid
		if false == t.tbUser.AddRecode(&item2add) {
			return nil, errors.New("userLogin failed in UserService userLogin")
		}

		user = &item2add
	}

	return user, nil
}